#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class BeijingshiPolicy(BaseTaxPolicySpider):
    name = 'beijingshi_policy'

    province = '北京市'
    city = '北京市'
    park = ''
    url = ''
    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Sec-Fetch-Dest": "document",
            "Sec-Fetch-Mode": "navigate",
            "Sec-Fetch-Site": "none",
            "Sec-Fetch-User": "?1",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
    }

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['北京市人民政府', '', 'https://www.beijing.gov.cn/zhengce/zhengcefagui/'],
            ['北京市人民政府', '', 'https://www.beijing.gov.cn/zhengce/zfwj/zfwj2016/szfwj/'],
            ['北京市人民政府', '', 'https://www.beijing.gov.cn/zhengce/zfwj/zfwj2016/bgtwj/'],
            ['北京市人民政府', '', 'https://www.beijing.gov.cn/zhengce/gfxwj/'],
            ['北京市发展和改革委员会', '', 'https://fgw.beijing.gov.cn/fgwzwgk/2024zcwj/index.htm'],
            ['北京市经济和信息化局', '', 'https://jxj.beijing.gov.cn/zwgk/2024zcwj/index.html'],
            ['北京市经济和信息化局', '', 'https://jxj.beijing.gov.cn/zwgk/2024zcwj/qtzc/'],
            ['北京市财政局', '', 'https://czj.beijing.gov.cn/zwxx/2024zcwj/index.html'],
            ['北京市财政局', '', 'https://czj.beijing.gov.cn/zwxx/2024zcwj/2024gfxwj/index.html'],
            ['北京市财政局', '', 'https://czj.beijing.gov.cn/zwxx/2024zcwj/2024qtwj/index.html'],
            ['北京市人力资源和社会保障局', '', 'https://rsj.beijing.gov.cn/xxgk/2024zcwj/index.html'],
            ['北京市规划和自然资源委员会', '', 'https://ghzrzyw.beijing.gov.cn/zhengwuxinxi/zcwj/index.html'],
            ['北京市商务局', '', 'https://sw.beijing.gov.cn/zwxx/2024zcwj/index.html'],
            ['北京市商务局', '', 'https://sw.beijing.gov.cn/zwxx/2024zcwj/2024gfxwj/'],
            ['北京市商务局', '', 'https://sw.beijing.gov.cn/zwxx/2024zcwj/2024flfg/'],
            ['北京市商务局', '', 'https://sw.beijing.gov.cn/zwxx/2024zcwj/qtfg/index.html'],
            ['北京市文化和旅游局', '', 'https://whlyj.beijing.gov.cn/zwgk/2024zcwj/index.html'],
            ['北京市市场监督管理局', '', 'https://scjgj.beijing.gov.cn/zwxx/2024zcwj/index.html'],
            ['北京经济技术开发区管理委员会', '', 'https://kfqgw.beijing.gov.cn/zwgkkfq/2024zcwj/xxyxzfwj/index.html'],

        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        # print(response.url)
        prev_item = response.meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True,
                                 meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//*[@class='default_news' or @class='list' or @class='ul-back' or @class='level-top-list' or @class='zcwj_right' or @class='sub_right' or @class='public_list']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9]")
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text:
                totalpage = response.xpath(""".""").re_first(r"var\s*countPage\s*=\s*(\d+)") or \
                            response.xpath(""".""").re_first(r"var\s*_nPageCount\s*=\s*(\d+)") or \
                            response.xpath("""//script""").re_first(r"var\s*countPage|pageCount\s*=\s*(\d+)") or \
                            response.xpath(""".""").re_first(r"Pager\(\{size\:\s*(\d+)")
                print('totalpage', totalpage, response.url)
                if totalpage and int(totalpage) > 1:
                    for page in range(1, int(totalpage) + 1):
                        url = response.url.replace('index.', f'index_{page}.')
                        if 'index' not in url:
                            url += f'index_{page}.html'
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print(response.url)
            else:
                print(response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()[:10] or response.xpath(
            """string(//meta[@name='firstpublishedtime']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl beijingshi_policy".split())
